<template>
  <!-- 价差套利 -->
  <div class="page-container-padding">
    <!-- 查询条件 -->
    <div>
      <span>
        <el-select v-model="queryVariety1" filterable style="width:120px;" size="mini" placeholder="选择品种">
          <el-option v-for="v in varietyList" :value="v.variety_en" :label="v.variety_long_name" :key="v.variety_en"></el-option>
        </el-select>
      </span>
      <span style="margin-left:6px;">
        <el-select v-model="contractYear1" size="mini" placeholder="合约年份" style="width:100px;">
          <el-option v-for="y in yearList" :value="y" :label="y+' 年'" :key="y"></el-option>
        </el-select>
      </span>
      <span style="margin-left:6px;">
        <el-select v-model="contractMonth1" size="mini" placeholder="合约月份" style="width:100px;">
          <el-option v-for="m in monthList" :value="m" :label="m+' 月'" :key="m"></el-option>
        </el-select>
      </span>
    </div>
    <div style="margin-top:6px;">
      <span>
        <el-select v-model="queryVariety2" filterable style="width:120px;" size="mini" placeholder="选择品种">
          <el-option v-for="v in varietyList" :value="v.variety_en" :label="v.variety_long_name" :key="v.variety_en"></el-option>
        </el-select>
      </span>
      <span style="margin-left:6px;">
        <el-select v-model="contractYear2" size="mini" placeholder="合约年份" style="width:100px;">
          <el-option v-for="y in yearList" :value="y" :label="y+' 年'" :key="y"></el-option>
        </el-select>
      </span>
      <span style="margin-left:6px;">
        <el-select v-model="contractMonth2" size="mini" placeholder="合约月份" style="width:100px;">
          <el-option v-for="m in monthList" :value="m" :label="m + ' 月'" :key="m"></el-option>
        </el-select>
      </span>
      <span style="margin-left:6px;"><el-button type="primary" size="mini" @click="getPriceDiff">价差计算</el-button></span>
      <span style="margin-left:6px;"><el-input-number style="width:80px;" v-model="yearCount" controls-position="right" :min="1" :max="10" size="mini"></el-input-number></span>
      <span style="margin-left:6px;"><el-button type="primary" size="mini" @click="getSeasonPriceDiff">季节图形</el-button></span>
    </div>
    <div style="line-height:18px;font-size:12px;color:#FF430D;">
      <span>提示：季节图形按钮前的数据设置，是设置要显示追溯到几年的前的数据。每组数据只分析合约到期前180天。</span>
    </div>
    <div style="margin-top:20px;">
      <!-- 显示图形 -->
      <div class="chart-box" v-loading="chartLoading" element-loading-text='数据加载中'>
        <vab-chart ref="chart" autoresize theme="vab-echarts-theme" :option="chartOption"></vab-chart>
      </div>
      <!-- 显示数据 -->
      <div v-show="seasonChartDataKeys.length > 0" style="margin: 10px 0">
        <span
          v-for="item in seasonChartDataKeys"
          :key="item"
          class="season-chart-key"
          @click="tableShowData(item)"
        >
          {{ item }}
        </span>
      </div>
      <div style="margin-top: 10px; width: 701px">
        <el-table border stripe :data="chartDataList">
          <el-table-column
            v-for="c in tableColumns"
            :key="c.prop"
            :prop="c.prop"
            :label="c.label"
            width="175px"
            align="right"
          ></el-table-column>
        </el-table>
      </div>
    </div>
  </div>
</template>

<script>
import VabChart from '@/plugins/echarts'
import { getYearList } from '@/utils/datetimeUtils'
import { getRuizyVariety } from '@/api/variety'
import { getArbitragePriceDiff, getSearsonArbitragePriceDiff } from '@/api/analysisData/arbitrage'
export default{
  components:{
    VabChart
  },
  data(){
    return {
      varietyList: [],
      yearList: [],
      monthList: ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12'],
      queryVariety1: null,
      contractYear1: null,
      contractMonth1: '01',
      queryVariety2: null,
      contractYear2: null,
      contractMonth2: '01',
      yearCount: 3,
      chartOptionInit: {
        color: ['#5b9bd5', '#ed7d31', '#ffc000', '#4472c4', '#70ad47', '#255e91',
                 '#9e480e', '#636363', '#997300', '#264478', '#43682b', '#7cafdd',
                 '#f1975a', '#ffcd33', '#698ed0', '#8cc168', '#327dc2', '#d26012'],
        title: {text: '图形标题', left: 'center'},
        grid: {
          top: '16%',
          left: '2%',
          right: '4%',
          bottom: '21',
          containLabel: true,
        },
        toolbox: {
          show: false,
          feature: {
            dataZoom: {
              yAxisIndex: 'none'
            },
            dataView: { readOnly: false },
            saveAsImage: {}
            }
          },
        tooltip: {
          trigger: 'axis'
        },
        xAxis: [
          {
            type: 'category',
            /*boundaryGap: false,*/
            data: [],
            axisTick: {
              alignWithLabel: true,
            }
          },
        ],
        yAxis: [
          {
            type: 'value',
            name: '价格',
            position: 'left',
            scale: true,
            min: null,
            max: null
          },
          {
            type: 'value',
            name: '价差',
            position: 'right',
            min: null,
            max: null,
            splitLine:{
              show: false
            }
          },
        ],
        series: [
          {
            name: '1',
            type: 'line',
            symbol: 'none',
            data: [],
          },
          {
            name: '2',
            type: 'line',
            symbol: 'none',
            data: []
          },
          {
            name: '价差(右)',
            type: 'bar',
            yAxisIndex: 1,
            data: []
          }
        ],
        legend: {
          bottom: 0,
          type: 'scroll',
          data: [] // {name: '1'}, {name: '2'},{name: '价差(右)'}
        }
      },
      chartOption: {title: {text: '暂无图形', left: 'center', top: '40%'}},
      chartDataList: [],
      tableColumns: [],
      chartLoading: false,

      seasonChartDataKeys: [],
      seasonChartData: {},
      seasonChartCurrentData: [],

    }
  },
  mounted() {
    this.yearList = getYearList(2018, true)
    this.contractYear1 = this.yearList[0]
    this.contractYear2 = this.yearList[0]

    getRuizyVariety({space: 'V00'}).then(res => {
      this.varietyList = res.data
    })
  },
  methods:{
    getPriceDiff(){
      if (!this.queryVariety1 || !this.queryVariety2){
        this.$baseMessage('请选择品种再操作!', 'error')
        return
      }
      const para = {
        c1: this.queryVariety1 + (this.contractYear1+'').slice(-2) + this.contractMonth1,
        c2: this.queryVariety2 + (this.contractYear2+'').slice(-2) + this.contractMonth2,
      }
      this.chartLoading = true
      this.seasonChartDataKeys = []
      this.chartDataList = []
      getArbitragePriceDiff(para).then(res => {
        const data = res.data
        const series1Name = data[0].c1
        const series2Name = data[0].c2
        let option = JSON.parse(JSON.stringify(this.chartOptionInit))
        option.title.text = series1Name + '-' + series2Name + '价差变化'
        option.xAxis[0].data = data.map(item=>item.quote_date)
        option.series[0].data = data.map(item=>item.p1)
        option.series[0].name = data[0].c1
        option.series[1].data = data.map(item=>item.p2)
        option.series[1].name = data[0].c2
        option.series[2].data = data.map(item=>item.pdiff)
        option.legend.data = [{name: series1Name}, {name: series2Name}, {name: '价差(右)'}]
        this.$refs.chart.clear()
        this.chartOption = option
        this.tableColumns = [
          {prop: 'quote_date', label: '日期'},
          {prop: 'p1', label: series1Name},
          {prop: 'p2', label: series2Name},
          {prop: 'pdiff', label: '价差'},
        ]
        this.chartDataList = data.reverse()
        this.chartLoading = false
      }).catch(err => {
        this.chartLoading = false
      })
    },

    getSeasonPriceDiff(){
      if (!this.queryVariety1 || !this.queryVariety2){
        this.$baseMessage('请选择品种再操作!', 'error')
        return
      }
      const para = {
        v1: this.queryVariety1,
        v2: this.queryVariety2,
        m1: this.contractMonth1,
        m2: this.contractMonth2,
        y: this.yearCount
      }
      this.chartLoading = true
      this.seasonChartDataKeys = []
      this.chartDataList = []
      getSearsonArbitragePriceDiff(para).then(res => {
        const data = res.data
        let option = JSON.parse(JSON.stringify(this.chartOptionInit))
        option.title.text = data.title
        option.xAxis[0].data = data.x_axis_data.map(item=>item.slice(4))
        option.xAxis[0].axisLabel = {
          rotate: 45,
          // formatter: (value,index)=>{return value.slice(4)}
        }
        option.yAxis = [{
          type: 'value',
          name: '价差',
          position: 'left',
          scale: true,
          min: null,
          max: null
        }]
        let series = []
        let legendData = []
        const valueData = data.value_data
        for (let k in valueData){
          let seriesObj = valueData[k]
          series.push({
            name: k,
            type: 'line',
            symbol: 'none',
            connectNulls: true,
            data: seriesObj.map(item => [item.uni_date.slice(4), item.pdiff])
          })
          legendData.push({name: k})
        }
        option.series = series
        option.legend.data = legendData
        this.$refs.chart.clear()
        this.chartOption = option
        this.chartLoading = false

        this.seasonChartData = valueData
        this.seasonChartDataKeys = series.map(i=>i.name)
        if (this.seasonChartDataKeys.length>0){
          this.tableShowData(this.seasonChartDataKeys[0])
        }

      }).catch(err => {
        this.chartLoading = false
      })
    },

      // 表格显示数据
      tableShowData(key) {
        this.chartDataList = JSON.parse(
          JSON.stringify(this.seasonChartData[key])
        ).reverse()
        if (this.chartDataList.length > 0) {
          this.tableColumns = [
            { prop: 'qdate', label: '日期' },
            { prop: 'p1', label: this.chartDataList[0].c1 },
            { prop: 'p2', label: this.chartDataList[0].c2 },
            { prop: 'pdiff', label: '价差' },
          ]
        }
      },
    },
}
</script>

<style scoped lang="scss">
  .chart-box {
    height: 400px;
    width: 700px;
    box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
  }
  .season-chart-key {
    padding: 4px 6px;
    margin-right: 10px;
    background: #349cfc;
    color: #eee;
    cursor: pointer;
    border-radius: 5px;
    &:hover {
      background: #0073fc;
      color: #fff;
    }
  }
</style>
